package com.oceansoft.mobile.biz.admin.service;

import static com.oceansoft.mobile.common.Constant.DB_OPER_ONE_SUCC;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.oceansoft.mobile.biz.admin.entity.BasesiteArticleNews;
import com.oceansoft.mobile.biz.admin.entity.BasesiteChannel;
import com.oceansoft.mobile.common.base.entity.Pager;
import com.oceansoft.mobile.common.base.entity.Query;
import com.oceansoft.mobile.common.base.entity.Result;
import com.oceansoft.mobile.common.dao.ICommonDao;

@Service
public class BasesiteServiceImpl implements IBasesiteService {
	@Resource
    private ICommonDao commonDao;
	
	@Override
	public Pager<BasesiteChannel> loadChannelByPage(long mer_id, Query query) {
		String page_sql = String.format("SELECT * FROM SITE_CHANNEL T WHERE T.MER_ID = ? %s", Query.getPageSQL("T", query));
        String count_sql = String.format("SELECT COUNT(*) FROM SITE_CHANNEL T WHERE T.MER_ID = ? %s", Query.getCountSQL("T", query));
        List<BasesiteChannel> list = commonDao.loadList(page_sql, BasesiteChannel.getFullRowMapper(), mer_id);
        int total = commonDao.getCount(count_sql, mer_id);
        return new Pager<BasesiteChannel>(total, query.getPage(), list); 
	}
	
	 public Result saveOrUpdate(BasesiteChannel channel) {
		 try{
			 if (null != channel) {
		            if (0 < channel.getSid()) { //更新操作
		                 commonDao.updateOne("UPDATE SITE_CHANNEL T SET T.name = :name,T.description = :description,T.mer_id = :mer_id,T.type=:type,T.type_val=:type_val WHERE T.SID = :sid", channel);
		                return new Result();
		            } else { //新增操作
		            	channel.setStatus(1);
		                commonDao.saveOne("INSERT INTO SITE_CHANNEL(name,description,mer_id,type,type_val,status) VALUES(:name,:description,:mer_id,:type,:type_val,:status)", channel);
		                return new Result();
		            }
		        } else {
		            return new Result(Result.FAILURE, "新增栏目失败");
		        }
		 }catch(Exception ex){
			 ex.printStackTrace();
		 }
		 return new Result(Result.FAILURE, "操作失败");
    }
	
	 public BasesiteChannel loadChannelById(long channelId) {
        String sql = "SELECT * FROM SITE_CHANNEL T WHERE T.SID = ?";
        return commonDao.loadOne(sql, BasesiteChannel.getFullRowMapper(), channelId);
    }

    @Override
	public Result deleteChannelById(long channelId) {
    	 int _num = commonDao.getCount("SELECT COUNT(*) FROM site_article T WHERE T.channel_id = ?", channelId);
         if (_num > 0) {
             return new Result(Result.FAILURE, "当前栏目存在内容，无法删除");
         } else {
             int rt = commonDao.deleteOne("DELETE FROM SITE_CHANNEL WHERE SID = ?", channelId);
             if (rt > 0)
                 return new Result();
         }
         return new Result(Result.FAILURE, "删除不成功");
	}

	@Override
	public List<BasesiteChannel> loadChannelByMerchantId(long merchantId) {
        String sql = "SELECT * FROM SITE_CHANNEL T WHERE T.MER_ID = ? AND T.STATUS = 1 and t.type='query' ";//必须栏目类型为query，即内部查询类的
        return commonDao.loadList(sql, BasesiteChannel.getRowMapper(), merchantId);
    }
	
	public List<BasesiteChannel> loadAllChannelByMerchantId(long merchantId) {
        String sql = "SELECT * FROM SITE_CHANNEL T WHERE T.MER_ID = ? AND T.STATUS = 1 ";//必须栏目类型为query，即内部查询类的
        return commonDao.loadList(sql, BasesiteChannel.getRowMapper(), merchantId);
    }
	
	
    
	@Override
	public Pager<BasesiteArticleNews> loadArticleNewsByPage(long merchantId, Query query) {
		String page_sql = String.format("SELECT t.*,t2.`name` channelName FROM SITE_ARTICLE T LEFT JOIN site_channel t2 ON t.channel_id=t2.sid WHERE T.MER_ID =? %s", Query.getPageSQL("T", query));
        String count_sql = String.format("SELECT COUNT(*) FROM SITE_ARTICLE T WHERE T.MER_ID = ? %s", Query.getCountSQL("T", query));
        List<BasesiteArticleNews> list = commonDao.loadList(page_sql, BasesiteArticleNews.getFullRowMapper(), merchantId);
        int total = commonDao.getCount(count_sql, merchantId);
        return new Pager<BasesiteArticleNews>(total, query.getPage(), list); 
	}
	
	 @Transactional
    public Result updateColunmByName(long pk, String prop, String val) {
        int rt = commonDao.updateColumn("SITE_ARTICLE","sid", pk, prop, val);
        if (DB_OPER_ONE_SUCC == rt)
            return new Result();
        return new Result(Result.FAILURE, "更新失败");
    }
	 
	public Result deleteArticleById(long sid) {
         int rt = commonDao.deleteOne("DELETE FROM SITE_ARTICLE WHERE SID = ?", sid);
         if (rt > 0)
             return new Result();
         return new Result(Result.FAILURE, "删除不成功");
	}
	
	 @Transactional
    public Result saveOrUpdate(BasesiteArticleNews art) {
        if (null != art) {
            if (0 < art.getSid()) {
                //更新产品信息表
                int base = commonDao.updateOne("UPDATE SITE_ARTICLE SET title =:title,description = :description,updateTime = :updateTime,content =:content,picCover = :picCover,channel_id = :channel_id WHERE SID = :sid", art);
//                //更新产品属性信息
//                List<Object[]> props = new ArrayList<Object[]>(2);
//                props.add(new Object[]{productVO.getReference().replaceAll("id\\s{0,}=\\s{0,}\"[\\w-_]*\"(\\s+)", "").replaceAll("class\\s{0,}=\\s{0,}\"[\\w-_]*\"(\\s+)", ""), productVO.getId(), PROP_KEY_REFERENCE});
//                props.add(new Object[]{productVO.getFeature().replaceAll("id\\s{0,}=\\s{0,}\"[\\w-_]*\"(\\s+)", "").replaceAll("class\\s{0,}=\\s{0,}\"[\\w-_]*\"(\\s+)", ""), productVO.getId(), PROP_KEY_FEATURE});
//                //批量保存属性
//                commonDao.updateBatch("UPDATE T_PRODUCT_ATTR T SET T.VAL = ? WHERE T.PID = ? AND T._KEY = ?", props);
//                //更新图片外键关联
//                if (StringUtils.hasText(productVO.getPhotos()) && productVO.getPhotos().split(",").length > 0) {
//                    String[] _pics = productVO.getPhotos().split(",");
//                    List<Object[]> params = new ArrayList<Object[]>(_pics.length);
//                    for (String pic : _pics) {
//                        if (StringUtils.hasText(pic)) {
//                            params.add(new Object[]{productVO.getId(), pic});
//                        }
//                    }
//                    commonDao.updateBatch("UPDATE T_PICS T SET T.PID = ? WHERE T.ID = ?", params);
//                }
                return new Result();
            } else {
                return saveArticle(art);
            }
        } else {
            return new Result(Result.FAILURE, "信息保存失败");
        }
    }
	 
	 private Result saveArticle(BasesiteArticleNews art) {
	        //保存产品主表信息
	        int pk = commonDao.saveOne("INSERT INTO SITE_ARTICLE(title,description,updateTime,content,picCover,mer_id,channel_id,status) VALUES(:title,:description,:updateTime,:content,:picCover,:mer_id,:channel_id,:status)", art);
//	        //保存产品属性信息
//	        List<ProductProperty> list = new ArrayList<ProductProperty>(2);
//	        list.add(new ProductProperty(PROP_KEY_REFERENCE, productVO.getReference(), "行程参考", pk, 1));
//	        list.add(new ProductProperty(PROP_KEY_FEATURE, productVO.getFeature(), "行程行色", pk, 2));
//	        //加载置顶图片
//	        commonDao.saveBatch("INSERT INTO T_PRODUCT_ATTR(_KEY,VAL,SORT,NAME,TID,PID) VALUES(:key,:val,:sort,:name,:templateId,:productId)", list);
	        //更新图片外键关联
	        if (StringUtils.hasText(art.getPhotos()) && art.getPhotos().split(",").length > 0) {
	            String[] _pics = art.getPhotos().split(",");
	            List<Object[]> params = new ArrayList<Object[]>(_pics.length);
	            for (String pic : _pics) {
	                if (StringUtils.hasText(pic)) {
	                    params.add(new Object[]{pk, pic});
	                }
	            }
	            commonDao.updateBatch("UPDATE T_PICS T SET T.PID = ? WHERE ID = ?", params);
	        }
	        if(pk>0)
	        	return new Result();
	        return new Result(Result.FAILURE, "保存失败");
	    }
	 
	 public BasesiteArticleNews loadArticleById(long sid) {
        String sql = "SELECT * FROM SITE_ARTICLE T WHERE T.SID = ?";
        BasesiteArticleNews art=null;
        try{
        	 art= commonDao.loadOne(sql, BasesiteArticleNews.getFullRowMapper2(), sid);
        }catch(Exception ex){
        	ex.printStackTrace();
        }
       
        return art;
    }
	 
	public List<BasesiteArticleNews> loadArticlesByMerchantId(long merchantId,long channel_id) {
        String sql = "SELECT * FROM SITE_ARTICLE T WHERE T.MER_ID = ? AND T.STATUS = 1 and t.channel_id=? "; 
        List<BasesiteArticleNews> list=null;
        try{
        	list= commonDao.loadList(sql, BasesiteArticleNews.getFullRowMapper(), merchantId,channel_id);
        }catch(Exception ex){
        	ex.printStackTrace();
        }
        return list;
    }
	public List<BasesiteArticleNews> loadArticlesListByMerchantId(long merchantId,long channel_id) {
		String sql = "SELECT sid,title,description,updateTime,picCover,mer_id FROM SITE_ARTICLE T WHERE T.MER_ID = ? AND T.STATUS = 1 and t.channel_id=? "; 
		List<BasesiteArticleNews> list=null;
		try{
			list= commonDao.loadList(sql, BasesiteArticleNews.getFullRowMapper3(), merchantId,channel_id);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return list;
	}
	
	
	public List<BasesiteArticleNews> loadArticles0PreNDays(int n){
		return commonDao.loadList("SELECT * from site_article t where sort=0 and (date(t.updateTime) BETWEEN DATE_SUB(CURDATE(), INTERVAL ?  DAY) and  DATE_SUB(CURDATE(), INTERVAL 1  DAY) ) ORDER BY t.updateTime desc",BasesiteArticleNews.getFullRowMapper3(),n);
	}
	public List<BasesiteArticleNews> loadArticlesByGroupPreNDays(int group,int n){
		return commonDao.loadList("SELECT * from site_article t where sort>0 and t.group=? and (date(t.updateTime) BETWEEN DATE_SUB(CURDATE(), INTERVAL ?  DAY) and  DATE_SUB(CURDATE(), INTERVAL 1  DAY) ) ORDER BY t.updateTime desc limit 2",BasesiteArticleNews.getFullRowMapper3(),group,n);
	}
	
	

}
